package com.markerhub.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.markerhub.common.lang.Result;
import com.markerhub.entity.RepairRequest;
import com.markerhub.service.RepairRequestService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Arrays;

/**
 * 维修申请Controller
 */
@Api(tags = "维修申请管理")
@RestController
@RequestMapping("/api/repair-request")
public class RepairRequestController extends BaseController {

    @Autowired
    private RepairRequestService repairRequestService;

    /**
     * 获取维修申请列表 - 分页
     */
    @ApiOperation(value = "获取维修申请列表", notes = "获取所有维修申请信息，支持分页查询")
    @PreAuthorize("hasAuthority('repair:request:list')")
    @GetMapping("/list")
    public Result list(RepairRequest request) {
        Page<RepairRequest> page = repairRequestService.page(getPage(), new QueryWrapper<RepairRequest>()
                .like(request.getDeviceId() != null, "device_id", request.getDeviceId())
                .like(request.getRequestCode() != null, "request_code", request.getRequestCode())
                .eq(request.getStatus() != null, "status", request.getStatus()));
        return Result.succ(200, "获取维修申请列表成功", page);
    }

    /**
     * 查询维修申请 - 分页
     */
    @ApiOperation(value = "查询维修申请", notes = "根据条件查询维修申请信息，支持分页")
    @PreAuthorize("hasAuthority('repair:request:query')")
    @GetMapping("/query")
    public Result query(RepairRequest request) {
        Page<RepairRequest> page = repairRequestService.page(getPage(), new QueryWrapper<RepairRequest>()
                .like(request.getDeviceId() != null, "device_id", request.getDeviceId())
                .like(request.getRequestCode() != null, "request_code", request.getRequestCode())
                .eq(request.getStatus() != null, "status", request.getStatus()));
        return Result.succ(200, "查询维修申请成功", page);
    }

    /**
     * 根据ID获取维修申请信息
     */
    @ApiOperation(value = "获取维修申请详情", notes = "根据申请ID获取指定维修申请的详细信息")
    @PreAuthorize("hasAuthority('repair:request:list')")
    @GetMapping("/detail/{id}")
    public Result detail(@PathVariable Long id) {
        RepairRequest request = repairRequestService.getById(id);
        return Result.succ(200, "获取维修申请信息成功", request);
    }

    /**
     * 创建维修申请
     */
    @ApiOperation(value = "新增维修申请", notes = "新增维修申请信息")
    @PreAuthorize("hasAuthority('repair:request:add')")
    @PostMapping("/add")
    public Result add(@Validated @RequestBody RepairRequest request) {
        // 生成申请编号：REQ + 年月日 + 4位随机数
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(new Date());
        String randomStr = String.format("%04d", (int)(Math.random() * 10000));
        String requestCode = "REQ" + dateStr + randomStr;
        request.setRequestCode(requestCode);
        
        request.setCreated(new Date());
        request.setUpdated(new Date());
        boolean saved = repairRequestService.save(request);
        return saved ? Result.succ(200, "创建维修申请成功", request) : Result.fail("创建维修申请失败");
    }

    /**
     * 更新维修申请
     */
    @ApiOperation(value = "更新维修申请", notes = "更新指定维修申请的详细信息")
    @PreAuthorize("hasAuthority('repair:request:update')")
    @PutMapping("/update")
    public Result update(@Validated @RequestBody RepairRequest request) {
        request.setUpdated(new Date());
        boolean updated = repairRequestService.updateById(request);
        return updated ? Result.succ(200, "更新维修申请成功", request) : Result.fail("更新维修申请失败");
    }

    /**
     * 删除单个维修申请
     */
    @ApiOperation(value = "删除维修申请", notes = "删除指定ID的维修申请信息")
    @PreAuthorize("hasAuthority('repair:request:delete')")
    @DeleteMapping("/delete/{id}")
    public Result deleteById(@PathVariable Long id) {
        boolean deleted = repairRequestService.removeById(id);
        return deleted ? Result.succ(200, "删除维修申请成功", null) : Result.fail("删除维修申请失败");
    }

    /**
     * 批量删除维修申请
     */
    @ApiOperation(value = "批量删除维修申请", notes = "批量删除多个维修申请信息")
    @PreAuthorize("hasAuthority('repair:request:delete')")
    @DeleteMapping("/delete")
    public Result delete(@RequestBody Long[] ids) {
        boolean deleted = repairRequestService.removeByIds(Arrays.asList(ids));
        return deleted ? Result.succ(200, "批量删除维修申请成功", null) : Result.fail("批量删除维修申请失败");
    }

    /**
     * 指派维修人员
     */
    @ApiOperation(value = "指派维修人员", notes = "为维修申请分配维修人员")
    @PreAuthorize("hasAuthority('repair:assign:process')")
    @PutMapping("/assign")
    public Result assign(@RequestBody AssignDto data) {
        RepairRequest request = repairRequestService.getById(data.getRequestId());
        if (request == null) {
            return Result.fail("维修申请不存在");
        }
        
        request.setRepairUserId(data.getAssigneeId());
        if (data.getRepairRemarks() != null) {
            request.setRepairRemarks(data.getRepairRemarks());
        }
        request.setUpdated(new Date());
        request.setStatus(2); // 维修中状态
        
        boolean updated = repairRequestService.updateById(request);
        return updated ? Result.succ(200, "指派维修人员成功", request) : Result.fail("指派维修人员失败");
    }

    /**
     * 完成维修
     */
    @ApiOperation(value = "完成维修", notes = "标记维修申请为已完成状态")
    @PreAuthorize("hasAuthority('repair:complete:confirm')")
    @PutMapping("/complete")
    public Result complete(@RequestBody CompleteDto data) {
        RepairRequest request = repairRequestService.getById(data.getRequestId());
        if (request == null) {
            return Result.fail("维修申请不存在");
        }
        
        request.setStatus(3); // 已完成状态
        request.setCompletionTime(new Date());
        request.setUpdated(new Date());
        request.setRepairRemarks(data.getRepairNotes());
        
        boolean updated = repairRequestService.updateById(request);
        return updated ? Result.succ(200, "完成维修成功", request) : Result.fail("完成维修失败");
    }

    /**
     * 更新申请状态
     */
    @ApiOperation(value = "更新申请状态", notes = "更新维修申请的状态")
    @PreAuthorize("hasAuthority('repair:request:status')")
    @PutMapping("/status")
    public Result updateStatus(@RequestBody StatusDto data) {
        RepairRequest request = repairRequestService.getById(data.getRequestId());
        if (request == null) {
            return Result.fail("维修申请不存在");
        }
        
        request.setStatus(data.getStatus());
        request.setUpdated(new Date());
        
        boolean updated = repairRequestService.updateById(request);
        return updated ? Result.succ(200, "更新申请状态成功", request) : Result.fail("更新申请状态失败");
    }

    // 辅助DTO类
    public static class AssignDto {
        private Long requestId;
        private Long assigneeId;
        private String repairRemarks; // 新增维修备注字段

        public Long getRequestId() {
            return requestId;
        }

        public void setRequestId(Long requestId) {
            this.requestId = requestId;
        }

        public Long getAssigneeId() {
            return assigneeId;
        }

        public void setAssigneeId(Long assigneeId) {
            this.assigneeId = assigneeId;
        }

        public String getRepairRemarks() {
            return repairRemarks;
        }

        public void setRepairRemarks(String repairRemarks) {
            this.repairRemarks = repairRemarks;
        }
    }

    public static class CompleteDto {
        private Long requestId;
        private String repairNotes;

        public Long getRequestId() {
            return requestId;
        }

        public void setRequestId(Long requestId) {
            this.requestId = requestId;
        }

        public String getRepairNotes() {
            return repairNotes;
        }

        public void setRepairNotes(String repairNotes) {
            this.repairNotes = repairNotes;
        }
    }

    public static class StatusDto {
        private Long requestId;
        private Integer status;

        public Long getRequestId() {
            return requestId;
        }

        public void setRequestId(Long requestId) {
            this.requestId = requestId;
        }

        public Integer getStatus() {
            return status;
        }

        public void setStatus(Integer status) {
            this.status = status;
        }
    }
}